package com.sigmatrix.h5.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.RowMapper;

public class SimpleRowMapper{
	
	static Logger logger = LoggerFactory.getLogger(SimpleRowMapper.class);
	
	public static <T> RowMapper<T> createDefault(Class<T> clazz){
		return new Mapper<T>(clazz);
	}
	
	static class Mapper<T> implements RowMapper<T>{
		
		private Class<T> clazz;
		
		@Override
		public T mapRow(ResultSet rs, int rowNum) throws SQLException {
			try {
				T t = clazz.newInstance();
				Field[] fields = clazz.getDeclaredFields();
				for (Field field : fields) {
					if("serialVersionUID".equals(field.getName())) continue;
					String columnName = CommonUtils.camelhumpToUnderline(field.getName());
					field.setAccessible(true);
					try{
						Object value = rs.getObject(columnName);
						if(value != null)field.set(t, value);
					}catch(Exception e){
						try {
							String beanType = field.getType().getSimpleName();
							if("Integer".equals(beanType)) beanType = "Int";
							Method method = rs.getClass().getDeclaredMethod("get"+beanType, String.class);
							field.set(t, method.invoke(rs, columnName));
						} catch (Exception e1) {
							logger.warn("jdbc类型转换异常，[{}]赋值失败,javaType:{}",columnName,field.getType());
							//e1.printStackTrace();
						}
					}
				}
				return t;
			} catch (InstantiationException | IllegalAccessException e) {
				e.printStackTrace();
			}
			return null;
		}


		public Mapper(Class<T> clazz) {
			super();
			this.clazz = clazz;
		}
		
	}
	
}
